package com.snowfield.lbcommon.utils;

import com.snowfield.lbcommon.config.SnowFieldConfig;
import com.snowfield.lbcommon.utils.commonsexec.CommonExecutor;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class CommandUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtils.class);

    /**
     * 重启或重载与负载均衡相关的服务
     *
     * @return 0:正常，其它异常
     */
    public static Integer lbRestart() {
        String shellCmd = "sh";
        String[] args = {SnowFieldConfig.getBasicConfigPath() + "/script/lb_restart.sh"};
        Integer result = CommonExecutor.exec(shellCmd, args, "");

        return result;
    }

    /**
     * 检测前端代理配置是否正常
     * <p>
     * /usr/sbin/haproxy -c -V -f
     * /usr/local/snowfield/haproxyConfig/haproxy-velocity-1.cfg &> /usr/local/snowfield/haproxyConfig/haproxy-velocity-1.log
     *
     * @return 0:正常，其它异常
     */
    public static Integer checkHaproxyConfigFile(String configFilePath, String resultFilePath) {
        String shellContent = "/usr/sbin/haproxy -c -V -f " + configFilePath + " &> " + resultFilePath;
        String checkShellPath = SnowFieldConfig.getHaConfigPath() + "/check.sh";
        try {
            FileUtils.write(new File(checkShellPath), shellContent, StandardCharsets.UTF_8);
            String shellCmd = "sh";
            String[] args = {checkShellPath};
            Integer result = CommonExecutor.execShell(shellCmd, args);

            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return -1;
    }

    /**
     * restart nginx服务
     *
     * @return
     */
    public static Integer restartNginx() {
        String shellCmd = "sh";
        String[] args = {SnowFieldConfig.getBasicConfigPath() + "/script/nginx_restart.sh"};
        Integer result = CommonExecutor.exec(shellCmd, args, "");

        return result;
    }

}